package com.ofek.applicationbase.forms;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.ofek.applicationbase.R;

public class QuestionAdapter extends ArrayAdapter<QuestionViewController> {
	private final Context context;
	private int submitRes;
	private boolean submitable;
	private FormFragment submitTo;
	public QuestionAdapter(final Context context, final ArrayList<QuestionViewController> questions) {
		 super(context,0,questions);
		 this.context = context;
		 submitRes = R.layout.form_submit;
	}
	public QuestionAdapter(final Context context,final List<QuestionViewController> objects) {
		super(context,0,objects);
		this.context = context;
		submitRes = R.layout.form_submit;
	}
	public QuestionAdapter(final Context context,final FormFragment submitTo,final List<QuestionViewController> objects) {
		super(context,0,objects);
		this.context = context;
		this.submitTo = submitTo;
		submitRes = R.layout.form_submit;
	}
	public void setSubmitResource(final int submitResource) {
		submitRes = submitResource;
	}
	@Override
	public boolean isEnabled(final int position) {
		return true;
	}
	@Override
	public boolean areAllItemsEnabled() {
		return true;
	}
	@Override
	public View getView(final int position, final View convertView, final ViewGroup parent) {
		if (position != getCount()-1 || !submitable) {
			QuestionView question = super.getItem(indices[position]).getQuestion();
			question.setLayoutParams(new ListView.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT));
			return question;
		}
		final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View inflate = inflater.inflate(submitRes,null);
		inflate.findViewById(R.id.submit).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(final View v) {
				if (context instanceof FormActivity) ((FormActivity) context).onSubmit();
				else submitTo.onSubmit();
			}
		});
		return inflate;
	}
	public void setSubmitable(final boolean submitable) {
		this.submitable = submitable;
	}
	private int[] indices;
	@Override
	public int getCount() {
		int n = super.getCount();
		indices = new int[super.getCount()];
		for (int i = 0,j=0 ; i < super.getCount() ; i++) {
			indices[i]=i;
			if (super.getItem(i).getQuestion().getVisibility()==View.GONE) n--;
			else indices[j++]=i;
		}
		return n + (submitable? 1 : 0);
	}
}
